#include "clientsdao.h"
#include <QSqlQuery>
#include <QVariant>



ClientsDAO::ClientsDAO(QObject *parent) :
    DatabaseConn(parent)
{

    tableName=new QString("clients");

}


int ClientsDAO::insertClient(QString firstname, QString lastname, int age)
{
    QVariant newId = -1;
    bool ret = false;

    if (db.isOpen())
    {
    //http://www.sqlite.org/autoinc.html
    // NULL = is the keyword for the autoincrement to generate next value

    QSqlQuery query;
    ret = query.exec(QString("insert into person values(NULL,'%1','%2',%3)").arg(firstname).arg(lastname).arg(age));

    // Get database given autoincrement value
    if (ret)
        {
        // http://www.sqlite.org/c3ref/last_insert_rowid.html
        newId = query.lastInsertId().toInt();
        }

    }
    return newId.Int;
}


Client* ClientsDAO::getClient(int clientId){

    openConnection();

    QSqlQuery query;

    bool ret = false;

    QString sql(" SELECT clientid, name,lastname,address,inscription_date from clients where clientid = ");
    sql.append(QString("%1").arg(clientId));

    qDebug(sql.toLatin1());

    ret = query.exec(sql);

    if(ret){
        qDebug("query executed");
    }

    query.first();

    qDebug(query.lastError().text().toLatin1());

    Client *client = new Client;
    client->setId(query.value(0).toInt());
    client->setName(&query.value(1).toString());
    client->setLastName(&query.value(2).toString());
    client->setAddress(&query.value(3).toString());
    client->setAddress(&query.value(3).toString());

    closeConnection();

    return client;
}

QList<Client *> ClientsDAO::getClients(){

    QList<Client*> test;

    openConnection();

    bool ret = false;

    QSqlQuery query;

    ret = query.exec(QString("SELECT clientid, name,lastname,address,inscription_date from clients"));

    if(ret){
        qDebug("query executed");
    }

    while (query.next()) {
        Client *client = new Client;
        client->setId(query.value(0).toInt());
        client->setName(&query.value(1).toString());
        client->setLastName(&query.value(2).toString());
        client->setAddress(&query.value(3).toString());
        client->setAddress(&query.value(3).toString());
        test<<client;
    }

    closeConnection();

    return test;
}
